var express = require('express');
var router = express.Router();
const rp = require("request-promise"); //将文件在当前js文件中进行关联
const token = require("jsonwebtoken");
const { getEncAse192 } = require("../utils/salt");

/* GET users listing. */
// 新增用户
router.post('/addNewAccount', async function (req, res, next) {
  console.log(req.body);
  const { password } = req.body;
  console.log(password);
  const newPassword = getEncAse192(password, "73");
  let conclusion = await rp({
    method: "POST",
    uri: "http://localhost:8080/users/register",
    body: {
      ...req.body, password: newPassword
    },
    json: true
  });
  res.send(conclusion);
});



//  判断用户是否登录
router.post("/isLogin", async (req, res) => {
  var loginUser = req.session.loginUser;
  var isLogined = !!loginUser; // 转换为布尔值
  res.send({
    isLogined: isLogined,
    name: loginUser || ''
  })
});


//  退出登录
router.get('/logout', function (req, res, next) {
  req.session.destroy(function (err) {
    if (err) {
      res.send({ ret_code: 2, ret_msg: '退出登录失败' });
      return;
    }
    // req.session.loginUser = "";
    res.clearCookie('identityKey');
    res.send({ ret_code: 0, ret_msg: '退出登录成功' });
  });
});

//  用户登陆
router.post('/login', async function (req, res, next) {
  let { password, username } = req.body

  // 加密密码
  let newPassword = getEncAse192(password, "73");
  // 向目标发送过程
  const data = await rp({
    method: "POST",
    uri: "http://localhost:8080/users/login",
    body: { ...req.body, password: newPassword },
    json: true
  })
  if (data.flag) {
    req.session.regenerate(function (err) {
      if (err) {
        // return res.send({ code: 2, msg: '登录失败' });
        return res.send({flag:false});
      }
      // 将登录成功⽤户名保存⾄ session 中
      req.session.loginUser = data.users//.username+'and__'+data.users.position;
      // res.send({ code: 0, msg: '登录成功' });
      res.send({flag:true,usersData:data.users});
    });
  } else {
    // res.send({ code: 1, msg: '账号或密码错误' });
    res.send({flag:false});
  }



});

module.exports = router;
